package cn.edu.nju.software.zp13.client.assignment4.sax.util;

import java.util.Collection;
import java.util.LinkedList;
import java.util.function.Predicate;

/**
 * a Collector of specific Type t with a collect criteria accepts an object
 * whose type is t ; It will test whether the object to be collected meets its
 * collect criteria. if ture,the collector's internal collection will add the
 * object.
 * 
 * @author Ivan
 *
 * @param <T>
 *            the type of object in this collector
 */
public class Collector<T> {
	private Collection<T> collectedObjet;
	private Predicate<T> collectCriteria;

	/**
	 * initialize field and make no criteria.
	 */
	public Collector() {
		collectedObjet = new LinkedList<>();
		collectCriteria = new Predicate<T>() {
			@Override
			public boolean test(Object t) {
				return true;
			}
		};
	}
	
	public Collector(Predicate<T> p){
		this.collectCriteria=p;
	}

	/**
	 * check whether the object meets this collector's collectCriteria,if true,
	 * add the object.
	 * 
	 * @param t
	 *            object going to be collected
	 */
	public void collect(T t) {
		if (collectCriteria.test(t)) {
			collectedObjet.add(t);
		}
	}

	/**
	 * return the number of object in this collector.
	 * 
	 * @return the number of object in this collector.
	 */
	public int size() {
		return collectedObjet.size();
	}

	/**
	 * returns an array containing all objects in this collector.
	 * 
	 * @param a
	 *            the array into which the object in this collector will be
	 *            stored.
	 * @return an array contains the object in this collector.
	 */
	public T[] toArray(T[] a) {
		return collectedObjet.toArray(a);
	}

	public void setCollectedObjet(Collection<T> collectedObjet) {
		this.collectedObjet = collectedObjet;
	}

	public void setCollectCriteria(Predicate<T> collectCriteria) {
		this.collectCriteria = collectCriteria;
	}

}
